﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using HaterAide.Cache.Interfaces;
using HaterAide.Interfaces;
using HaterAide.Mappings;
using HaterAide.SQL.Interfaces;
#endregion

namespace HaterAide.SQL.SQLServer
{
    /// <summary>
    /// The SQL Server provider
    /// </summary>
    public class Provider : IProvider
    {
        #region Private Functions

        private Utilities.SQL.DataClasses.Database GetDesiredDatabase()
        {
            SQLBuilder.SetupFunctions(Database);
            SQLBuilder.SetupStoredProcedures(Database);
            SQLBuilder.SetupAuditTables(Database);
            return Database;
        }

        private Utilities.SQL.DataClasses.Database GetCurrentDatabase()
        {
            string Database = Regex.Match(ConnectionString, "Initial Catalog=(.*?;)").Value.Replace("Initial Catalog=", "").Replace(";", "");
            string TempConnectionString = Regex.Replace(ConnectionString, "Initial Catalog=(.*?;)", "");
            if (Utilities.SQL.SQLServer.SQLServer.DoesDatabaseExist(Database, TempConnectionString))
            {
                return Utilities.SQL.SQLServer.SQLServer.GetDatabaseStructure(ConnectionString);
            }
            return null;
        }

        #endregion

        #region IProvider functions

        public override void Create()
        {
            Utilities.SQL.DataClasses.Database CurrentDatabase = GetCurrentDatabase();
            Utilities.SQL.DataClasses.Database DesiredDatabase = GetDesiredDatabase();
            if (CurrentDatabase == null)
            {
                Utilities.SQL.SQLServer.SQLServer.CreateDatabase(DesiredDatabase, ConnectionString);
            }
            else
            {
                Utilities.SQL.SQLServer.SQLServer.UpdateDatabase(DesiredDatabase, CurrentDatabase, ConnectionString);
            }
        }

        public override bool Save(object Object, Session CurrentSession)
        {
            if (!this.Write)
                return false;
            bool ReturnValue = false;
            if (Object is IEnumerable)
            {
                ReturnValue = SQLBuilder.Save(ConnectionString, Object, ClassManager, MappingManager, CurrentSession);
                IEnumerable ObjectList = (IEnumerable)Object;
                foreach (object TempObject in ObjectList)
                {
                    Type ObjectType = TempObject.GetType();
                    if (TempObject is IHaterAideObject
                        && ((IHaterAideObject)TempObject).Update0)
                    {
                        while (ClassManager[ObjectType] == null)
                        {
                            ObjectType = ObjectType.BaseType;
                        }
                        IClass ClassDefinition = ClassManager[ObjectType];
                        IAttributeMap Mapping = MappingManager.ClassMappings[ObjectType];
                        if (Mapping != null
                            && ClassDefinition != null
                            && Cache != null)
                        {
                            object IDObject = ObjectType.GetProperty(Mapping.IDProperties[0].Name).GetValue(TempObject, null);
                            if (Cache.Exists(ClassDefinition.OriginalType.Name + "_" + IDObject.ToString()))
                                Cache.Delete(ClassDefinition.OriginalType.Name + "_" + IDObject.ToString());
                        }
                    }
                }
            }
            else
            {
                ReturnValue = SQLBuilder.Save(ConnectionString, Object, ClassManager, MappingManager, CurrentSession);
                Type ObjectType = Object.GetType();
                if (Object is IHaterAideObject
                    && ((IHaterAideObject)Object).Update0)
                {
                    while (ClassManager[ObjectType] == null)
                    {
                        ObjectType = ObjectType.BaseType;
                    }
                    IClass ClassDefinition = ClassManager[ObjectType];
                    IAttributeMap Mapping = MappingManager.ClassMappings[ObjectType];
                    if (Mapping != null
                        && ClassDefinition != null
                        && Cache != null)
                    {
                        object IDObject = ObjectType.GetProperty(Mapping.IDProperties[0].Name).GetValue(Object, null);
                        if (Cache.Exists(ClassDefinition.OriginalType.Name + "_" + IDObject.ToString()))
                            Cache.Delete(ClassDefinition.OriginalType.Name + "_" + IDObject.ToString());
                    }
                }
            }
            return ReturnValue;
        }

        public override void Delete(object Object, Session CurrentSession)
        {
            if (!this.Write)
                return;
            if (Object is IEnumerable)
            {
                IEnumerable ObjectList = (IEnumerable)Object;
                IClass ClassDefinition = null;
                IAttributeMap ClassMapping = null;
                foreach (object TempObject in ObjectList)
                {
                    Type ObjectType = TempObject.GetType();
                    while (!MappingManager.ClassMappings.ContainsKey(ObjectType))
                    {
                        ObjectType = ObjectType.BaseType;
                    }
                    ClassDefinition = ClassManager[ObjectType];
                    ClassMapping = MappingManager.ClassMappings[ObjectType];
                    if (ClassDefinition != null && Cache != null)
                    {
                        object IDObject = ObjectType.GetProperty(ClassMapping.IDProperties[0].Name).GetValue(TempObject, null);
                        if (Cache.Exists(ClassDefinition.OriginalType.Name + "_" + IDObject.ToString()))
                            Cache.Delete(ClassDefinition.OriginalType.Name + "_" + IDObject.ToString());
                    }
                }
                SQLBuilder.Delete(ConnectionString, Object, ClassDefinition, ClassMapping, ClassManager, MappingManager, CurrentSession);
            }
            else
            {
                Type ObjectType = Object.GetType();
                IClass ClassDefinition = null;
                IAttributeMap ClassMapping = null;
                while (!MappingManager.ClassMappings.ContainsKey(ObjectType))
                {
                    ObjectType = ObjectType.BaseType;
                }
                ClassDefinition = ClassManager[ObjectType];
                ClassMapping = MappingManager.ClassMappings[ObjectType];
                if (ClassDefinition != null && Cache != null)
                {
                    object IDObject = ObjectType.GetProperty(ClassMapping.IDProperties[0].Name).GetValue(Object, null);
                    if (Cache.Exists(ClassDefinition.OriginalType.Name + "_" + IDObject.ToString()))
                        Cache.Delete(ClassDefinition.OriginalType.Name + "_" + IDObject.ToString());
                }
                SQLBuilder.Delete(ConnectionString, Object, ClassDefinition, ClassMapping, ClassManager, MappingManager, CurrentSession);
            }
        }

        public override T SelectByID<T>(object IDValue, Session CurrentSession, object Object)
        {
            if (!this.Read)
                return default(T);
            IClass TempClassDefinition = null;
            try
            {
                TempClassDefinition = ClassManager[typeof(T)];
            }
            catch { throw; }
            if (Cache.Exists(TempClassDefinition.OriginalType.Name + "_" + IDValue.ToString()))
                return (T)Cache[TempClassDefinition.OriginalType.Name + "_" + IDValue.ToString()];
            T ReturnValue = SQLBuilder.SelectByID<T>(ConnectionString, IDValue, ClassManager, MappingManager, CurrentSession);
            if (Cache != null && ReturnValue != null)
            {
                Cache.Save(TempClassDefinition.OriginalType.Name + "_" + IDValue.ToString(), ReturnValue);
            }
            return ReturnValue;
        }

        public override List<T2> SelectListByID<T1, T2>(object IDValue, string FieldName, Session CurrentSession)
        {
            if (!this.Read)
                return new List<T2>();
            IClass InputClassDefinition = null;
            IClass OutputClassDefinition = null;
            try
            {
                InputClassDefinition = ClassManager[typeof(T1)];
                OutputClassDefinition = ClassManager[typeof(T2)];
            }
            catch { InputClassDefinition = null; OutputClassDefinition = null; }
            return SQLBuilder.SelectListByID<T2>(ConnectionString, IDValue, InputClassDefinition, OutputClassDefinition, ClassManager, MappingManager, FieldName, CurrentSession);
        }

        public override List<T> SelectAll<T>(Session CurrentSession)
        {
            if (!this.Read)
                return new List<T>();
            IClass TempClassDefinition = null;
            try
            {
                TempClassDefinition = ClassManager[typeof(T)];
            }
            catch { TempClassDefinition = null; }
            return SQLBuilder.SelectAll<T>(ConnectionString, TempClassDefinition, ClassManager, MappingManager, CurrentSession);
        }

        public override List<T> SelectWhere<T>(HaterAide.SQL.Interfaces.SQL.IClause<T> Clause, HaterAide.SQL.Interfaces.SQL.IClause<T> OrderBy, Session CurrentSession, int Start, int End)
        {
            if (!this.Read)
                return new List<T>();
            IClass TempClassDefinition = null;
            try
            {
                TempClassDefinition = ClassManager[typeof(T)];
            }
            catch { TempClassDefinition = null; }
            return SQLBuilder.SelectWhere<T>(ConnectionString, TempClassDefinition, ClassManager, MappingManager, Clause, OrderBy, CurrentSession, Start, End);
        }

        public override List<T> SelectStoredProcedure<T>(string StoredProcedureName, List<HaterAide.SQL.Interfaces.SQL.IVariable> Variables, Session CurrentSession)
        {
            if (!this.Read)
                return new List<T>();
            IClass TempClassDefinition = null;
            try
            {
                TempClassDefinition = ClassManager[typeof(T)];
            }
            catch { TempClassDefinition = null; }
            return SQLBuilder.SelectStoredProcedure<T>(ConnectionString, TempClassDefinition, ClassManager, MappingManager, StoredProcedureName, Variables, CurrentSession);
        }

        public override List<T> SelectSQLText<T>(string SQLText, List<HaterAide.SQL.Interfaces.SQL.IVariable> Variables, Session CurrentSession)
        {
            if (!this.Read)
                return new List<T>();
            IClass TempClassDefinition = null;
            try
            {
                TempClassDefinition = ClassManager[typeof(T)];
            }
            catch { TempClassDefinition = null; }
            return SQLBuilder.SelectSQLText<T>(ConnectionString, TempClassDefinition, ClassManager, MappingManager, SQLText, Variables, CurrentSession);
        }

        public override ICache Cache { get; set; }

        #endregion
    }
}